//
//  XiuGaiXinXiViewController.m
//  NC-Trendy
//
//  Created by ljd on 16/2/25.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "XiuGaiXinXiViewController.h"

#import "NCTrendyHeader.pch"

@interface XiuGaiXinXiViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *userIconImageView;
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
@property (weak, nonatomic) IBOutlet UITextField *userZoneField;

@end

@implementation XiuGaiXinXiViewController

#pragma mark -完成修改信息的方法
- (IBAction)completeChangeBtnClick:(UIButton *)sender {
    //菊花显示
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //菊花显示时候的文字
    hud.labelText = @"正在修改";
    //如果用户除了头像之外，有没有填写的信息，显示提示
    if ([self.userNameField.text isEqualToString:@""]||[self.userZoneField.text isEqualToString:@""]) {
            AppDelegate *appdelegate = [AppDelegate shareAppDelegate];
            [self showAlertView:@"用户信息不能为空，请您输入您的信息"];
        //将用户的信息继续放在textField里面，方便用户
            self.userNameField.text = appdelegate.userModel.user_name;
            self.userZoneField.text = appdelegate.userModel.user_zone;
        //提示信息之后，菊花要隐藏
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }else{
            //没有未填写的信息
            //判断用户是否选择了头像,如果没有选择执行下列方法
            if (self.userIconImageView.image == nil) {
                //找出单例
                AppDelegate *appdelegate = [AppDelegate shareAppDelegate];
                //设定请求路径
                NSString *path = [NSString stringWithFormat:@"http://localhost:8888/nongchao/Home/User/updateInfo"];
                //设定http请求的管理员
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                //设定发送请求的时候 需要用到的端口信息字典
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                param[@"name"] = self.userNameField.text;
                param[@"zone"] = self.userZoneField.text;
                //因为不需要用户知道自己的帐号的在数据库里面的位置，但是端口需要uid 这个信息，所以，找到单例里面的模型的user——id信息
                param[@"uid"] = [NSString stringWithFormat:@"%d",appdelegate.userModel.user_id];
                //发送POST请求
                [manager POST:path parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"%@",responseObject);
                    //用返回的数据判断是否修改成功
                    [self panDuanShiFouXiuGaiChengGongWithDic:responseObject];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    if (error) {
                        NSLog(@"%@",error);
                        [self showAlertView:@"网络请求失败，请重新尝试"];
                    }
                }];
            }else{
                //如果用户选择了头像，调用修改用户头像方法
                NSString *path = [NSString stringWithFormat:@"http://localhost:8888/nongchao/Home/User/updateIcon"];
                
            }
           
        }
    
}

//方法封装：判断是否修改成功
-(void)panDuanShiFouXiuGaiChengGongWithDic:(NSDictionary *)dic {
    if ([dic[@"status"] isEqualToString:@"1"]) {
        [self showAlertView:dic[@"data"]];
        AppDelegate *appdelegate = [AppDelegate shareAppDelegate];
        appdelegate.userModel.user_name = self.userNameField.text;
        appdelegate.userModel.user_zone = self.userZoneField.text;
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([dic[@"status"] isEqualToString:@"0"]){
        [self showAlertView:dic[@"data"]];
    }else{
        [self showAlertView:dic[@"data"]];
    }
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}


#pragma mark -进入相机选择用户头像的方法
- (IBAction)chooseUserIconImageBtnClick:(UIButton *)sender {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [picker setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    [picker setAllowsEditing:YES];
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

//方法封装:显示提示
-(void)showAlertView:(NSString *)alert {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:alert delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

#pragma mark -UIImagePickerController 代理实现
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    NSData *data = UIImageJPEGRepresentation(image, 0);
    [data writeToFile:[self imagePath] atomically:YES];
    self.userIconImageView.image = [UIImage imageWithContentsOfFile:[self imagePath]];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(NSString *)imagePath {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"iconImage.jpg"];
    return path;
}

#pragma mark -页面每次将要显示执行方法
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *appdelegate = [AppDelegate shareAppDelegate];
    
    if (appdelegate.userModel) {
        self.userNameField.text = appdelegate.userModel.user_name;
        self.userZoneField.text = appdelegate.userModel.user_zone;
        if (!appdelegate.userModel.user_icon) {
            self.userIconImageView.image = nil;
            
        }else{
            self.userIconImageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithContentsOfURL:[NSURL URLWithString:appdelegate.userModel.user_sicon] encoding:NSUTF8StringEncoding error:nil]];
        }
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
